package com.focusai.efairy.ui.activity.location;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.focusai.efairy.R;
import com.focusai.efairy.business.location.AMapLocationManager;
import com.focusai.efairy.business.location.LocationManagerFactory;
import com.focusai.efairy.model.location.Location;
import com.focusai.efairy.model.location.LocationCallback;
import com.focusai.efairy.model.location.LocationManager;
import com.focusai.efairy.ui.adapter.SelectLocationAdapter;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.utils.log.Log;
import com.focusai.efairy.utils.permission.PermissionListener;
import com.focusai.efairy.utils.permission.PermissionUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luo_guangwen on 2017/9/4.
 */

public class AMapSelectLocationActivity extends SwipeBackBaseActivity implements View.OnClickListener, PoiSearch.OnPoiSearchListener {
    //    protected LocationModel mLocationModel;
    private static final String TAG = AMapSelectLocationActivity.class.getName();
    public final static String KEY_SELECT_LOCATION_ITEM = "key_select_location";
    private static final int REQUEST_CODE_SEARCH = 0x11;
    private RecyclerView mRecyclerView;
    private MapView mMapView;
    private AMap mAMap;
    private double mLat, mLon, mCircleLat, mCircleLon;
    private PoiSearch mPoiSearch;
    private PoiSearch.Query mPoiQuery;
    private CircleOptions mCircleOptions;
    private int mOffestMeters = 10;
    private final static int POI_SEARCH_COUNT = 50, POI_SEARCH_BOUND = 500;

    private LocationManager mLocationManager;
    private Location mLocation;
    private MarkerOptions mMarkerOptions;
    private SelectLocationAdapter mAdapter;
    private List<Location> locationList;
    private boolean isMove = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_amap_select_location);
        mMapView = (MapView) findViewById(R.id.set_checkpoint_mapView);
        mMapView.onCreate(savedInstanceState);
        initView();
        if (getIntent() != null && getIntent().getExtras() != null) {
            mLocation = (Location) getIntent().getExtras().get(KEY_SELECT_LOCATION_ITEM);
            if (mLocation != null) {
                mLat = mLocation.getmLatitude();
                mLon = mLocation.getmLongitude();
            }
        }
        setDefaultValues();
        initLocation();
        checkLoactionPermission();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.control).setTitle(R.string.sure);
        MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ADD) {
            if (locationList.size() > mAdapter.getSelectPosition() && mAdapter.getSelectPosition() >= 0)
                mLocation = locationList.get(mAdapter.getSelectPosition());
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable(KEY_SELECT_LOCATION_ITEM, mLocation);
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initView() {
        mRecyclerView = findView(R.id.rcyc_view);
        findView(R.id.search_header).setOnClickListener(this);
        setCenterTitleName("选择地址");
    }

    private void setUpMapIfNeeded() {
        if (mAMap == null) {
            try {
                mAMap = mMapView.getMap();
            } catch (OutOfMemoryError outOfMemoryError) {
                outOfMemoryError.printStackTrace();
                mMapView.setVisibility(View.GONE);
            }
            if (null != mAMap) {
                setUpMap();
            }
        }
    }

    private AMap.OnCameraChangeListener onCameraChangeListener = new AMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {
            if (!isMove) {
                return;
            }
            if (null != cameraPosition && null != cameraPosition.target) {
                mLat = cameraPosition.target.latitude;
                mLon = cameraPosition.target.longitude;
                mCircleLat = cameraPosition.target.latitude;
                mCircleLon = cameraPosition.target.longitude;
            } else {
                mCircleLat = mLat;
                mCircleLon = mLon;
            }
        }

        @Override
        public void onCameraChangeFinish(CameraPosition cameraPosition) {
            if (isMove) {
                doSearchQuery();
                drawCircleInMap();
            }
            isMove = true;
        }
    };

    private void setUpMap() {
        LatLng lntlng = new LatLng(mLat, mLon);
        mMarkerOptions = createMarkerOptions();
        mMarkerOptions.position(lntlng);
        mAMap.setOnCameraChangeListener(onCameraChangeListener);
        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lntlng, 17));
        mAMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mLat = latLng.latitude;
                mLon = latLng.longitude;
                mAMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng)); //移动到对应位置
//                doSearchQuery();
            }
        });
    }

    private MarkerOptions createMarkerOptions() {
        MarkerOptions mo = new MarkerOptions();
        mo.anchor(0.5f, 0.5f);
        mo.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_map_address_yellow));
        return mo;
    }

    protected void doSearchQuery() {
        mPoiQuery = new PoiSearch.Query("", "", "");
        mPoiQuery.setPageSize(POI_SEARCH_COUNT);
        mPoiQuery.setPageNum(0);
        mPoiQuery.setCityLimit(false);
        mPoiQuery.setDistanceSort(false);
        mPoiSearch = new PoiSearch(this, mPoiQuery);
        mPoiSearch.setOnPoiSearchListener(this);
        mPoiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(mLat, mLon), POI_SEARCH_BOUND, true));
        mPoiSearch.searchPOIAsyn();
    }

    private void drawCircleInMap() {
//        //添加范围圆圈
        double circleRadius = mOffestMeters;

        if (mAMap == null) {
            return;
        }
        LatLng circleLatLng = new LatLng(mCircleLat, mCircleLon);
        if (mCircleOptions == null) {
            mCircleOptions = new CircleOptions();
        }
        mCircleOptions.center(circleLatLng);
        mCircleOptions.radius(circleRadius);
        mCircleOptions.strokeWidth(2f);
        mCircleOptions.fillColor(getResources().getColor(R.color.btn_normal_half));
        mCircleOptions.strokeColor(getResources().getColor(R.color.btn_normal_half));
        mAMap.clear();
        mAMap.addCircle(mCircleOptions);
    }

    private void initLocation() {
        mLocationManager = LocationManagerFactory.getLocationManager(getApplicationContext());
        mLocationManager.setLocationCallback(new LocationCallback() {
            @Override
            public void locationSuccess(Location location) {
                mLocation = location;
                mLat = location.getmLatitude();
                mLon = location.getmLongitude();
                closeSingleDialog();
                stopMyLocation();
                setUpMapIfNeeded();
                doSearchQuery();
            }

            @Override
            public void locationFail(int errorCode, String errorMessage) {
                closeSingleDialog();
                stopMyLocation();
                showToastOnUiThread("定位失败");
                if (errorCode == 12){
                    checkLoactionPermission();
                }
            }
        });
    }

    private void startMyLocation() {
        if (!hasAddress()) {
            showSingleDialog("正在定位...");
            mLocationManager.startLocation();
        } else {
            setUpMapIfNeeded();
        }
    }

    private boolean hasAddress() {
        return (mLat != 0.0 && mLon != 0.0);
    }

    private void stopMyLocation() {
        mLocationManager.stopLocation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void setDefaultValues() {
        locationList = new ArrayList<>();
        mAdapter = new SelectLocationAdapter(getContext());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.refreshData(locationList);
        mAdapter.setListener(new SelectLocationAdapter.OnItemLayoutClickListener() {
            @Override
            public void onItemClick(Location location, int position) {
                mLocation = location;
                mLat = location.getmLatitude();
                mLon = location.getmLongitude();
                isMove = false;
                mAMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(mLat, mLon)));
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_header:
                Intent intent = new Intent(getContext(), AMapSearchLocationActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SEARCH);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SEARCH:
                    if (data != null && data.getExtras() != null) {
                        mLocation = (Location) data.getExtras().getSerializable(KEY_SELECT_LOCATION_ITEM);
                        mLat = mLocation.getmLatitude();
                        mLon = mLocation.getmLongitude();
                        stopMyLocation();
                        setUpMapIfNeeded();
                        mAMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(mLat, mLon)));
                    }
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int state) {
        if (state != 0 && poiResult != null && poiResult.getPois() != null) {
            List<PoiItem> list = poiResult.getPois();
            locationList.clear();
//            if (mLocation != null){
//                locationList.add(mLocation);
//            }
            for (PoiItem item : list) {
                locationList.add(AMapLocationManager.spoiItemToLocation(item));
            }
            if (locationList.size() > 0) {
                mAdapter.setSelectPosition(0);
                mAdapter.setSelectPosition(0);
            }
            mAdapter.refreshData(locationList);

        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {
        Log.D(TAG, poiItem.toString());

    }

    private void checkLoactionPermission(){
        checkPermission(PermissionUtil.PERMISSION_LOCATION, new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, List<String> grantedList) {
                startMyLocation();
            }

            @Override
            public void onFailed(int requestCode, List<String> deniedList) {
                showToast("没定位权限");
                finish();
            }
        }, Manifest.permission.ACCESS_COARSE_LOCATION);
    }
}
